<template>
    <!-- 当有API ID时显示API详情 -->
    <ApiDetailView v-if="currentMode === 'view'" :apiId="currentApiId" :projectId="projectId" @edit="handleEdit"
        :key="currentApiId" />
    <ApiDetailEdit v-else :apiId="currentApiId" :projectId="projectId" :currentMode="currentMode" @save="handleSave"
        @cancel="handleCancel" />
</template>

<script setup>
import { ref, watch, inject } from 'vue';
import { useRoute } from 'vue-router';
import router from '@/router';
import { ElMessageBox } from 'element-plus';
import ApiDetailView from './ApiDetailView.vue';
import ApiDetailEdit from './ApiDetailEdit.vue';
import { useEditorStore } from "@/store/modules/editStatus.ts";

const props = defineProps({
    mode: {
        type: String,
    },
    apiId: [String, Number],
    projectId: [String, Number]
});

// 本地状态管理
const route = useRoute();
const currentMode = ref(props.mode);
const currentApiId = ref(props.apiId);
const emit = defineEmits(['hasChange']);
const editorStore = useEditorStore();

// 注入父组件提供的刷新方法
const refreshSidebar = inject('refreshSidebar');

// 处理未保存更改的确认
const confirmLoseChanges = async () => {
    if (editorStore.hasUnsavedChanges) {
        try {
            await ElMessageBox.confirm(
                '您有未保存的更改，切换后将丢失，是否继续？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            );
            editorStore.setHasUnsavedChanges(false);
            return true;
        } catch {
            return false;
        }
    } else {
        return true;
    }
};

// 监听props变化，同步本地状态
watch(() => props.mode, (newMode) => {
    currentMode.value = newMode;
});

watch(() => props.apiId, async (newId) => {
    currentApiId.value = newId;
});

// 切换到编辑模式
const handleEdit = () => {
    router.replace({
        path: route.path,
        query: { ...route.query, mode: 'edit' }
    });
};

// 保存处理
const handleSave = async (data) => {
    editorStore.setHasUnsavedChanges(false);
    router.replace({
        path: `/project/${route.params.id}/api/${data.id}`, // 使用动态项目ID和API ID
        query: { ...route.query, mode: 'view' }
    });
    if (refreshSidebar && data.id) {
        await refreshSidebar(Number(data.id));
    }
};


// 取消编辑
const handleCancel = async () => {
    if (!await confirmLoseChanges()) return;
    router.replace({
        path: route.path,
        query: { ...route.query, mode: 'view' }
    });
};
</script>